'use strict';
const express = require('express');
const jwt = require('jsonwebtoken');
const bodyParser = require('body-parser');
const app = express();
const SECRET_KEY = "qiumanwohenni"
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: false
}));

function generateToken(id) {
    return jwt.sign({
        userid: id
    }, SECRET_KEY, {
        expiresIn: 10
    });
}
app.post('/login', (req, res)=> {
    if (req.body.name && req.body.name === 'gay' && req.body.psd && req.body.psd === '123') {
        res.json({
            token: generateToken('gay')
        });
    } else {
        res.status(401).end('UnAuthorization');
    }
});
app.get('/user', function(req, res, next) {
    if (!req.query.token) {
        return res.status(401).end('UnAuthorization');
    }
    jwt.verify(req.query.token, SECRET_KEY, function(err, decode) {
    	if(err){
    		if(err instanceof jwt.TokenExpiredError) {
    			return res.status(401).end('Token expired');
    		}
    		return res.status(401).end('UnAuthorization')
    	}
    	req.user = decode.userid;
    	next();
    });
}, function(req, res) {
	res.end('nice doing user: '+ req.user);
})


app.listen('3000', err => {
    if (err) {
        console.log(err);
    } else {
        console.log('server start on port 3000');
    }
});